﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace MyNoteBook
{
    public partial class frmMain : Form
    {
        /// <summary>
        /// 文件名属性，用于储存文件名
        /// </summary>
        private string mfileName;
        public string fileName
        {
            get
            {
                return mfileName;
            }
            set
            {
                mfileName = value;
                if (!string.IsNullOrEmpty(value))
                {
                    this.Text = string.Format("{0}-记事本", mfileName);
                }
                else
                {
                    this.Text = "无标题 - 记事本";
                }
            }

        }

        private void 新建NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //设置文本内容为空
            this.textMainContent.Text = "";
            this.fileName = "";
        }

        private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "打开文本文件";
                openFileDialog.FileName = "*.txt";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    FileStream fileStream = new FileStream(openFileDialog.FileName, FileMode.Open);
                    StreamReader streamReader = new StreamReader(fileStream, Encoding.Default);
                    this.textMainContent.Text = streamReader.ReadToEnd();
                    streamReader.Close();
                    fileStream.Close();
                    //更新存储的文件名
                    this.fileName = openFileDialog.FileName;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "保存文本文件";
                saveFileDialog.FileName = "*.txt";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create);
                    StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default);
                    streamWriter.Write(this.textMainContent.Text);
                    streamWriter.Close();
                    fileStream.Close();
                    //更新存储的文件名
                    this.fileName = saveFileDialog.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //文件名不存在，直接调用“另存为”菜单处理程序
            if (string.IsNullOrEmpty(this.fileName))
            {
                另存为ToolStripMenuItem_Click(null, null);
            }
            else
            {
                try
                {
                    //文件名存在，直接存盘
                    FileStream fileStream = new FileStream(this.fileName, FileMode.Create);
                    StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default);
                    streamWriter.Write(this.textMainContent.Text);
                    streamWriter.Close();
                    fileStream.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }

        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //将文档内容打印出来，出于简化的目的，这里只打印一页的内容，多页打印请同学们自己解决
            //Graphics可以理解为打印时的那支画笔
            Graphics g = e.Graphics;
            //打印画刷设置，设为黑色实线
            Brush brush = new SolidBrush(Color.Black);
            //打印字体，使用编辑框相同的字体、字号
            Font font = this.textMainContent.Font;
            g.DrawString(this.textMainContent.Text, font, brush, new RectangleF(0, 0, e.PageBounds.Width, e.PageBounds.Height));
        }

        private void 打印PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.printDialog1.ShowDialog() == DialogResult.OK)
            {
                //将打印设置传给打印文档
                this.printDocument1.PrinterSettings = this.printDialog1.PrinterSettings;
                //将页面设置传给打印文档
                //this.printDocument1.DefaultPageSettings = this.pageSetupDialog1.PageSettings;
                //开始打印
                this.printDocument1.Print();
            }
        }

        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public Stack<string> contentStack { get; set; }

        public frmMain()
        {
            InitializeComponent();
            //初始化栈，这是使用前必要准备的
            this.contentStack = new Stack<string>();
        }

        private void txtMainContent_TextChanged(object sender, EventArgs e)
        {
            this.contentStack.Push(this.textMainContent.Text);
            this.撤销ToolStripMenuItem.Enabled = (this.contentStack.Count > 0);
        }

        private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.contentStack.Count > 0)
                this.contentStack.Pop();
            if (this.contentStack.Count > 0)
                this.textMainContent.Text = this.contentStack.Pop();
        }

        private void txtMainContent_KeyDown(object sender, KeyEventArgs e)
        {
            CheckSelection();
        }

        private void txtMainContent_MouseUp(object sender, MouseEventArgs e)
        {
            CheckSelection();
        }

        private void CheckSelection()
        {
            //剪切板中储存的信息
            if (Clipboard.ContainsText())
            {
                this.粘贴PToolStripMenuItem.Enabled = true;
            }
            else
            {
                this.粘贴PToolStripMenuItem.Enabled = false;
            }
            if (this.textMainContent.SelectedText == "")
            {
                //没有选择的信息
                this.剪切TToolStripMenuItem.Enabled = false;
                this.复制CToolStripMenuItem.Enabled = false;
                this.删除LToolStripMenuItem.Enabled = false;
            }
            else
            {
                //有选择的信息
                this.剪切TToolStripMenuItem.Enabled = true;
                this.复制CToolStripMenuItem.Enabled = true;
                this.删除LToolStripMenuItem.Enabled = true;
            }
            //strLeft为光标前的字符串
            string strLeft = this.textMainContent.Text.Substring(0, this.textMainContent.SelectionStart);
            strLeft = "\r\n"+strLeft ;
            //最后一个回车出现的位置
            int lastIndex = strLeft.LastIndexOf('\n');
            //光标在本行内所在的列数
            int intCol = this.textMainContent.SelectionStart - lastIndex + 1;
            //计算行数要数前面的回车数量
            var arrayString = strLeft.Split('\n');
            int intRow = arrayString.Length - 1;
            //显示设置
            this.toolStripStatusLabel1_Message.Text = string.Format($"第{0}行,第{1}列", intRow, intCol);
        }

        private void 剪切TToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.textMainContent.SelectedText != "")
            {
                Clipboard.SetText(this.textMainContent.SelectedText);
                this.textMainContent.SelectedText = "";
                CheckSelection();
            }
        }

        private void 复制CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(this.textMainContent.SelectedText);
            CheckSelection();
        }


        private void 粘贴PToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strInsertText = Clipboard.GetText();
            this.textMainContent.SelectedText = strInsertText;
        }


        private void 删除LToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.textMainContent.SelectedText = "";
        }

        private static frmSearch frmsearch { get; set; }

        private void 查找FToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmsearch = new frmSearch();
            frmsearch.Search += frm_Search;
            frmsearch.Show();
        }

        public struct SearchConcent
        {
            public string text;
            public bool IsUp;
            public bool IsCaseSensitive;
            public SearchConcent(string strSearchText, bool mIsUp, bool mIsCaseSensitive)
            {
                text = strSearchText;
                IsUp = mIsUp;
                IsCaseSensitive = mIsCaseSensitive;
            }
        }

        public SearchConcent searchConcent { get; set; }

        private void frm_Search(string strSearchText, bool IsUp, bool IsCaseSensitive)
        {
            //先将查询条件储存起来
            this.searchConcent = new SearchConcent(strSearchText, IsUp, IsRestrictedWindow);
            //开始查询
            searchNext();
        }

        private void searchNext()
        {
            //搜索结果的位置
            int intAns = -1;
            //光标所在位置
            int indexNow;
            //要搜索的字符串，是光标前还是光标后，由searchConcent.IsUp决定
            if (this.searchConcent.IsUp)
            {
                //向上搜索
                indexNow = this.textMainContent.SelectionStart;
                string strSearchString = this.textMainContent.Text.Substring(0, indexNow);
                //大小写是否敏感问题
                if (this.searchConcent.IsCaseSensitive)
                {
                    intAns = strSearchString.LastIndexOf(this.searchConcent.text, StringComparison.CurrentCulture);
                }
                else
                {
                    intAns = strSearchString.LastIndexOf(this.searchConcent.text, StringComparison.CurrentCultureIgnoreCase);
                }
            }
            else
            {
                //向下搜索
                indexNow = this.textMainContent.SelectionStart + this.textMainContent.SelectionLength;
                string strSearchString = this.textMainContent.Text.Substring(indexNow);
                //大小写是否敏感问题
                if (this.searchConcent.IsCaseSensitive)
                {
                    intAns = strSearchString.IndexOf(this.searchConcent.text, StringComparison.CurrentCulture);
                }
                else
                {
                    intAns = strSearchString.IndexOf(this.searchConcent.text, StringComparison.CurrentCultureIgnoreCase);
                }
            }
            if (intAns < 0)
            {
                MessageBox.Show(String.Format($"找不到{0}", searchConcent.text));
            }
            else
            {
                //激活本窗口，不然无法显示搜索结果
                this.Activate();
                //如果是向下搜索，需要加上光标开始时的坐标
                if (!searchConcent.IsUp)
                {
                    intAns += indexNow;
                    //设定搜索结果
                    this.textMainContent.SelectionStart = intAns;
                    this.textMainContent.SelectionLength = this.searchConcent.text.Length;
                }
            }
        }

        private void 查找下一个NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.searchConcent.text))
            {
                searchNext();
            }
            else
            {
                查找FToolStripMenuItem_Click(null, null);  //如果没有开始过搜索，则直接调用“搜索”菜单响应程序
            }
        }

        private void txtMainContent_TextChange(object sender, EventArgs e)
        {
            this.contentStack.Push(this.textMainContent.Text);
            this.撤销ToolStripMenuItem.Enabled = (this.contentStack.Count > 0);
            //文本改变要进行的检查
            CheckText();
        }

        private void CheckText()
        {
            this.查找FToolStripMenuItem.Enabled = (this.textMainContent.Text != "");
            this.查找下一个NToolStripMenuItem.Enabled = (this.textMainContent.Text != "");
        }

        private void 全选AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.textMainContent.SelectionStart = 0;
            this.textMainContent.SelectionLength = this.textMainContent.Text.Length;
        }

        private void 时间日期DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.textMainContent.SelectionLength = 0;
            this.textMainContent.SelectedText = System.DateTime.Now.ToString();
            this.textMainContent.SelectionLength = 0;
        }

        private void 自动换行WToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.自动换行WToolStripMenuItem.Checked )
            {
                //自动换行状态
                this.转到GToolStripMenuItem.Enabled = false;
                this.状态栏SToolStripMenuItem.Checked = false;
                this.状态栏SToolStripMenuItem.Enabled = false;
                //自动换行
                this.textMainContent.WordWrap = true;
                //输入区只包括纵向滚动条
                this.textMainContent.ScrollBars = ScrollBars.Vertical;
            }
            else
            {
                //不自动换行状态
                this.转到GToolStripMenuItem.Enabled = true ;
                this.状态栏SToolStripMenuItem.Enabled = true ;
                //不自动换行
                this.textMainContent.WordWrap = false;
                //输入区包括双向滚动条
                this.textMainContent.ScrollBars = ScrollBars.Both;
            }
        }

        private void 状态栏SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.statusStrip1.Visible = this.状态栏SToolStripMenuItem.Checked;
        }

        private void 转到GToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmGoto frm = new frmGoto();
            if (frm.ShowDialog()==DialogResult.OK )
            {
                int intLine;
                if (int.TryParse(frm.Tag .ToString (),out intLine)) //防止用户输入的不是整数
                {
                    if (intLine>0)
                    {
                        int intPostion = 0;
                        if (intLine >1)
                        {
                            for (int i = 1; i < intLine ; i++)
                            {
                                int intNext = this.textMainContent.Text.IndexOf('\n', intPostion);
                                if (intPostion >=0)
                                {
                                    intPostion = intNext + 1;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        if (intPostion >=0)
                        {
                            //存在指定的行
                            this.textMainContent.SelectionStart = intPostion;
                            this.textMainContent.SelectionLength = 0;
                            //控件的内容滚动到光标位置
                            this.textMainContent.ScrollToCaret();
                            //刷新状态栏显示
                            CheckSelection();
                        }
                    }
                }
            }
        }

        private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.fontDialog1 .ShowDialog ()==DialogResult.OK)
            {
                this.textMainContent.Font = this.fontDialog1.Font;
            }
        }

        private void 关于记事本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new frmAbout()).ShowDialog();
        }
    }
}
